<?php

namespace Platform\Services\Scenario;

use Platform\Services\BaseService;

class ScenarioService extends BaseService {

    public function getScenario($id, $img, $nickname) {
        $this->userImg = $img;
        $this->userName = $nickname;
        $scenarioModel = Model("Scenario/Scenario");
        $redisScenarioInfoKey = getRedisKey("SCENARIO", "SCENARIO_", $id);
        if ($this->redisCache->exists($redisScenarioInfoKey)) {
            $redisScenarioInfo = $this->redisCache->get($redisScenarioInfoKey);
            $scenarioInfo = unserialize($redisScenarioInfo);
        } else {
            $scenarioInfo = $scenarioModel->getDataById($id, "title,img,id");
            if (empty($scenarioInfo)) {
                E("剧本不存在");
            }
            $redisScenarioInfo = serialize($scenarioInfo);
            $result = $this->redisCache->set($redisScenarioInfoKey, $redisScenarioInfo);
            if ($result) {
//                $this->redisCache->expire($redisScenarioInfoKey, 3600);
            }
            unset($result);
        }
        $playerId = 0;
        $startId = 0;

        $redisScenarioRoleListKey = getRedisKey("SCENARIO", "SCENARIO_ROLE_LIST_", $id);
        if ($this->redisCache->exists($redisScenarioRoleListKey)) {
            $redisScenarioRoleList = $this->redisCache->get($redisScenarioRoleListKey);
            $scenarioRoleList = unserialize($redisScenarioRoleList);
        } else {
            $scenarioRoleList = $this->getScenarioRole($id, $playerId);
            $redisScenarioRoleList = serialize($scenarioRoleList);
            $result = $this->redisCache->set($redisScenarioRoleListKey, $redisScenarioRoleList);
            if ($result) {
//                $this->redisCache->expire($redisScenarioRoleListKey, 3600);
            }
            unset($result);
        }

        $redisScenarioForestListKey = getRedisKey("SCENARIO", "SCENARIO_FOREST_LIST_", $id);
        if ($this->redisCache->exists($redisScenarioForestListKey)) {
            $redisScenarioForestList = $this->redisCache->get($redisScenarioForestListKey);
            $scenarioForestList = unserialize($redisScenarioForestList);
        } else {
            $scenarioForestList = $this->getScenarioForest($id);
            $redisScenarioForestList = serialize($scenarioForestList);
            $result = $this->redisCache->set($redisScenarioForestListKey, $redisScenarioForestList);
            if ($result) {
//                $this->redisCache->expire($redisScenarioForestListKey, 3600);
            }
            unset($result);
        }

        $redisScenarioNodelistKey = getRedisKey("SCENARIO", "SCENARIO_NODE_LIST_", $id);
        $redisScenarioStartidKey = getRedisKey("SCENARIO", "SCENARIO_STARTID_", $id);
        $redisScenarioForestImgListKey = getRedisKey("SCENARIO", "SCENARIO_FOREST_IMG_LIST_", $id);
        if ($this->redisCache->exists($redisScenarioNodelistKey)) {
            $redisScenarioNodelist = $this->redisCache->get($redisScenarioNodelistKey);
            $scenarioNodelist = unserialize($redisScenarioNodelist);
            $startId = $this->redisCache->get($redisScenarioStartidKey);
            $redisForestImgList = $this->redisCache->get($redisScenarioForestImgListKey);
            $forestImgList = unserialize($redisForestImgList);
        } else {
            $scenarioTreeNodeList = $this->getScenarioTreeNode($id);
            $scenarioNodelist = $this->getScenarioNode($id, $playerId, $scenarioRoleList);
            $scenarioNodelist = $this->getNodeTree($scenarioNodelist, $scenarioTreeNodeList, $startId);
            $result = $this->redisCache->set($redisScenarioStartidKey, $startId);
            if ($result) {
//                $this->redisCache->expire($redisScenarioStartidKey, 3600);
            }
            unset($result);
            $redisScenarioNodelist = serialize($scenarioNodelist);
            $result = $this->redisCache->set($redisScenarioNodelistKey, $redisScenarioNodelist);
            if ($result) {
//                $this->redisCache->expire($redisScenarioNodelistKey, 3600);
            }
            unset($result);
            $forestImgList = array();
            foreach ($scenarioNodelist as $key => $value) {
                //第四幕能触发长歌结局
                if ($value["forestId"] == "12") {
                    $value["forestId"] = "4";
                }
                //第七幕能触发强强侠结局
                if ($value["forestId"] == "11") {
                    $value["forestId"] = "7";
                }
                //第八幕能触发卷卷结局
                if ($value["forestId"] == "10") {
                    $value["forestId"] = "8";
                }
                //第九幕能触发甄一一所有结局
                if ($value["forestId"] == "13" || $value["forestId"] == "14" || $value["forestId"] == "15") {
                    $value["forestId"] = "9";
                }

                //处理所有素材ID
                if ($value['foregroundImgUrl'] != "") {
                    $forestImgList[$value["forestId"]][] = $value['foregroundImgUrl'];
                }

                if ($value['backgroundImgUrl'] != "") {
                    $forestImgList[$value["forestId"]][] = $value['backgroundImgUrl'];
                }
                if ($value['type'] == 3) {
                    $extend = json_decode($value['extend'], true);
                    foreach ($extend['dialogue'] as $dk => $dv) {
                        if ($dv['foregroundImgUrl'] != "") {
                            $forestImgList[$value["forestId"]][] = $dv['foregroundImgUrl'];
                        }
                    }
                }
            }
            foreach ($forestImgList as $key => $value) {
                $forestImg = array_flip(array_flip($value));
                $forestImgList[$key] = array_values($forestImg);
            }
            $redisForestImgList = serialize($forestImgList);
            $result = $this->redisCache->set($redisScenarioForestImgListKey, $redisForestImgList);
            if ($result) {
//                $this->redisCache->expire($redisScenarioForestImgListKey, 3600);
            }
            unset($result);
        }
        $this->transformNodeVariableValue($scenarioNodelist, $this->userImg, $this->userName);
        $scenarioInfo['startId'] = $startId;
        $result['scenarioInfo'] = $scenarioInfo;
        $result['node'] = $scenarioNodelist;
        $result['role'] = $scenarioRoleList;
        $result['forestImgList'] = $forestImgList;
        return $result;
    }

    private function getScenarioForest($id) {
        $condition['scenarioId'] = $id;
        $scenarioForestModel = Model("Scenario/ScenarioForest");
        $scenarioForestList = $scenarioForestModel->getLists($condition, array(), "", 0, 0, "");
        return $scenarioForestList;
    }

    private function getScenarioTreeNode($id) {
        $condition['scenarioId'] = $id;
        $scenarioTreeNodeModel = Model("Scenario/ScenarioTreeNode");
        $scenarioTreeNodeList = $scenarioTreeNodeModel->getLists($condition, array("id,nodeId,pid,jumpId"), "", 0, 0, "");
        return $scenarioTreeNodeList;
    }

    private function getScenarioNode($id, $playerId, $scenarioRoleList = false) {
        $condition['scenarioId'] = $id;
        $scenarioNodeModel = Model("Scenario/ScenarioNode");
        $materialList[] = array();
        $scenarioNodelist = $scenarioNodeModel->getLists($condition, array(), "", 0, 0, "");
        $middleArray = array();
        foreach ($scenarioNodelist as $key => $value) {
            //处理所有素材ID
            $value['foregroundImgUrl'] = "";
            if ($value['foregroundImgId'] != 0) {
                $materialInfo = $this->getMaterialById($value['foregroundImgId'], $materialList);
                $value['foregroundImgUrl'] = $materialInfo['url'];
            }
            unset($value['foregroundImgId']);

            $value['videoUrl'] = "";
            if ($value['videoId'] != 0) {
                $materialInfo = $this->getMaterialById($value['videoId'], $materialList);
                $value['videoUrl'] = $materialInfo['url'];
            }
            unset($value['videoId']);

            $value['musicUrl'] = "";
            if ($value['musicId'] != 0) {
                $materialInfo = $this->getMaterialById($value['musicId'], $materialList);
                $value['musicUrl'] = $materialInfo['url'];
            }
            unset($value['musicId']);

            $value['backgroundImgUrl'] = "";
            if ($value['backgroundImgId'] != 0) {
                $materialInfo = $this->getMaterialById($value['backgroundImgId'], $materialList);
                $value['backgroundImgUrl'] = $materialInfo['url'];
            }
            unset($value['backgroundImgId']);


            $value['backgroundMusicUrl'] = "";
            if ($value['backgroundMusicId'] != 0) {
                $materialInfo = $this->getMaterialById($value['backgroundMusicId'], $materialList);
                $value['backgroundMusicUrl'] = $materialInfo['url'];
            }
            unset($value['backgroundMusicId']);

            $value['roleImg'] = "";
            $value['roleName'] = "";
            //兑换一下roleId的属性
            if ($scenarioRoleList && $value['roleId'] != 0) {
                if ($value['roleId'] == $playerId) {
                    $value['roleImg'] = '{$userImg}';
                    $value['roleName'] = '{$userName}';
                } else {
                    $value['roleImg'] = $scenarioRoleList[$value['roleId']]['img'];
                    $value['roleName'] = $scenarioRoleList[$value['roleId']]['name'];
                }
            }
//            unset($value['roleId']);

            if ($value['type'] == 3) {
                $extend = json_decode($value['extend'], true);
                foreach ($extend['dialogue'] as $dk => $dv) {
                    $extend['dialogue'][$dk]["foregroundImgUrl"] = "";
                    if ($dv['foregroundImgId'] != 0) {
                        $materialInfo = $this->getMaterialById($dv['foregroundImgId'], $materialList);
                        $extend['dialogue'][$dk]["foregroundImgUrl"] = $materialInfo['url'];
                    }
                    $extend['dialogue'][$dk]['roleImg'] = "";
                    $extend['dialogue'][$dk]['roleName'] = "";
                    if ($dv['roleId'] != 0) {
                        if ($dv['roleId'] == $playerId) {
                            $extend['dialogue'][$dk]['roleImg'] = '{$userImg}';
                            $extend['dialogue'][$dk]['roleName'] = '{$userName}';
                        } else {
                            $extend['dialogue'][$dk]['roleName'] = $scenarioRoleList[$dv['roleId']]['name'];
                        }
                    }
                    unset($dv['foregroundImgId']);
                }
                $value['extend'] = $extend;
            }
//            unset($value['forestId']);
            unset($value['scenarioId']);
            unset($value['name']);
            $middleArray[$value['id']] = $value;
        }
        return $middleArray;
    }

    /**
     * 获取素材
     * @param type $id
     * @param type $materialList
     */
    private function getMaterialById($id, &$materialList) {
        $materialModel = Model("Scenario/Material");
        if (empty($materialList[$id])) {
            $materialInfo = $materialModel->getDataById($id);
            $materialList[$id] = $materialInfo;
        } else {
            $materialInfo = $materialList[$id];
        }
        return $materialInfo;
    }

    private function getScenarioRole($id, &$playerId) {
        $condition['scenarioId'] = $id;
        //获取所有角色信息并且以角色id做key
        $scenarioRoleModel = Model("Scenario/ScenarioRole");
        $scenarioRoleList = $scenarioRoleModel->getLists($condition, array("id,name,imgId,isPlayer"), "", 0, 0, "");
        if ($scenarioRoleList) {
            $materialModel = Model("Scenario/Material");
            $materialList = $materialModel->getDateListBySelectDate($scenarioRoleList, "imgId", "id,url", "imgId");
            foreach ($scenarioRoleList as $key => $value) {
                if ($value['isPlayer'] == 1) {
                    $playerId = $value['id']; //赋值玩家ID
                }
                $scenarioRoleList[$key]['img'] = "";
                foreach ($materialList as $mk => $mv) {
                    if ($value['imgId'] == $mv['imgId']) {
                        $scenarioRoleList[$key]['img'] = $mv['url'];
                    }
                }
                unset($scenarioRoleList[$key]['imgId']);
            }
            $middleArray = array();
            foreach ($scenarioRoleList as $key => $value) {
                $middleArray[$value['id']] = $value;
            }
            $scenarioRoleList = $middleArray;
        }
        return $scenarioRoleList;
    }

    private function getNodeTree($scenarioNodelist, $scenarioTreeNodeList, &$startId) {
        foreach ($scenarioNodelist as $key => $value) {
            if (!$startId) {
                $startId = $value['id'];
            }
            $scenarioNodelist[$key]['nextStep'] = $this->getNodeNext($scenarioTreeNodeList, $key);
        }
        return $scenarioNodelist;
    }

    private function getNodeNext($scenarioTreeNodeList, $nodeId) {
        $result = array();
        foreach ($scenarioTreeNodeList as $key => $value) {
            if ($value['pid'] == $nodeId) {
                $result[] = $value['nodeId'];
            }
            if ($value['nodeId'] == $nodeId && $value['jumpId'] != 0) {
                $result[] = $value['jumpId'];
            }
        }
        if (count($result) == 1) {
            return $result[0];
        }
        return $result;
    }

    /**
     * 解析redis里面缓存剧本的变量
     * @param type $node
     * @param type $userImg
     * @param type $userName
     */
    private function transformNodeVariableValue(&$node, $userImg, $userName) {
        foreach ($node as $key => $value) {
            if (is_array($value)) {
                $this->transformNodeVariableValue($value, $userImg, $userName);
                $node[$key] = $value;
            }
            if ($key == "character" || $key == "roleName" || $key == "roleImg") {
                $node[$key] = $value = str_replace('{$userName}', $userName, $value);
                $node[$key] = $value = str_replace('{$userImg}', $userImg, $value);
            }
        }
    }

}

?>
